package com.charonmc.commands;

import com.charonmc.CharonLogin;
import com.charonmc.utils.Md5Utils;
import com.charonmc.utils.TokenUtils;
import com.charonmc.utils.mysql.SqlManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Register implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (sender instanceof Player) {
            Player player = (Player) sender;
            if (CharonLogin.loginPlayers.contains(player)){
                return true;
            }
            BukkitRunnable queryPlayerRegister = new BukkitRunnable() {
                @Override
                public void run() {
                    try {
                        boolean isPlayerRegister;
                        //数据库查询参数
                        SqlManager SqlManager = new SqlManager("charonmc");
                        isPlayerRegister = SqlManager.createQuery()
                                .inTable("players")
                                .selectColumns("player_id")
                                .addCondition("player_name", sender.getName())
                                .build()
                                .execute()
                                .isNull();
                        if (isPlayerRegister) {
                            //没注册
                            //参数错误
                            if (args.length != 2) {
                                sender.sendMessage("§7");
                                sender.sendMessage("§7你需先进行注册");
                                sender.sendMessage("§7/register §f&l密码 重复密码");
                            }
                            //参数正确，其他判断
                            else {
                                //密码太长
                                if (args[0].length() > 20 || args[1].length() > 20) {
                                    sender.sendMessage("§c您输入的密码过长");
                                } else if (args[0].length() < 6  || args[1].length() < 6) {
                                    sender.sendMessage("§c您输入的密码过短");
                                } else if (!Objects.equals(args[0], args[1])) {
                                    sender.sendMessage("§c两个密码不一致！");
                                } else if (!isAlphaNumeric(args[0])){
                                    sender.sendMessage("§c密码中含有非法字符！");
                                } else {
                                    //开始注册
                                    String[] names = {"player_name", "password"};
                                    Object[] params = {player.getName(), Md5Utils.getMd5(args[0], player)};
                                    int id = SqlManager.createInsert()
                                            .inTable("players")
                                            .addColumnNames(names)
                                            .addParams(params)
                                            .build()
                                            .execute()
                                            .getGeneratedKey();
                                    names = new String[]{"player_id"};
                                    params = new Object[]{id};
                                    SqlManager.createInsert()
                                            .inTable("player_set")
                                            .addColumnNames(names)
                                            .addParams(params)
                                            .build()
                                            .execute();
                                    sender.sendMessage("§a§l注册成功");
                                    CharonLogin.loginPlayers.add(player);
                                    SqlManager.createUpdate()
                                            .inTable("players")
                                            .addColumnNames(new String[]{"token"})
                                            .addParams(new Object[]{TokenUtils.getToken(player)})
                                            .addCondition("player_id", id)
                                            .build()
                                            .execute();
                                }
                            }
                        } else {
                            //注册了
                            sender.sendMessage("§c您已经注册过了！");
                        }
                        SqlManager.close();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            queryPlayerRegister.runTaskAsynchronously(CharonLogin.instance);
        } else {
            sender.sendMessage("§c§l该命令只能由玩家执行！");
        }
        return true;
    }

    /***
     * 判断字符串是否由字母和数字组成
     * @param s 判断的字符串
     * @return 结果
     */
    public static boolean isAlphaNumeric(String s){
        Pattern p = Pattern.compile("[0-9a-zA-Z]+");
        Matcher m = p.matcher(s);
        return m.matches();
    }
}
